package com.bytech.user.biz.service.friendChain.Impl;

import java.util.Arrays;
import java.util.Date;
import java.util.Optional;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.blogUser.BlogUser;
import com.bytech.common.biz.entity.blogUser.BlogUserAgent;
import com.bytech.common.biz.entity.friendChain.FriendChain;
import com.bytech.common.biz.entity.friendChain.FriendChainDto;
import com.bytech.common.biz.entity.friendChain.FriendChainQuery;
import com.bytech.common.biz.enums.friendChain.FriendChainAuditStatusEnum;
import com.bytech.common.config.AppGlobalConstants;
import com.bytech.common.utils.StringUtils;
import com.bytech.user.biz.mapper.friendChain.FriendChainMapper;
import com.bytech.user.biz.service.blogUser.BlogUserService;
import com.bytech.user.biz.service.friendChain.FriendChainService;
import com.bytech.common.biz.service.base.BasicServiceImpl;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author Zhao
 * @Create 2021-10-08
 */
@Service
public class FriendChainServiceImpl extends BasicServiceImpl<FriendChainMapper, FriendChain> implements FriendChainService {

    @Resource
    private BlogUserService blogUserService;
    @Resource
    private FriendChainMapper friendChainMapper;

    @Override
    @Transactional
    public BaseResult<String> applyFriendChain(FriendChain chain, HttpServletRequest request, HttpServletResponse response, BlogUserAgent userAgent) {
        BaseResult<String> checkResult = checkChain(chain);
        if (checkResult.isFailure()) {
            return checkResult;
        }
        boolean newCookie = false;
        if (userAgent == null || StringUtils.isBlank(userAgent.getId())) {
            BlogUser register = new BlogUser();
            register.setName(chain.getFriendName());
            register.setAvatarUrl(chain.getFriendAvatar());
            BaseResult<BlogUser> registerResult = blogUserService.register(register);
            if (registerResult.isFailure()) {
                return BaseResult.<String>error("友链申请失败：用户注册失败：" + registerResult.getMsg()).build();
            }
            newCookie = true;
            userAgent = new BlogUserAgent(registerResult.getData());

        }
        if (newCookie) {
            Cookie[] cookies = request.getCookies();
            if (!ArrayUtils.isEmpty(cookies)) {
                Optional<Cookie> opCookie = Arrays.stream(cookies).filter(e -> e.getName().equals(AppGlobalConstants.BLOG_USER_COOKIE_KEY)).findFirst();
                if (!opCookie.isPresent()) {
                    Cookie cookie = new Cookie(AppGlobalConstants.BLOG_USER_COOKIE_KEY, userAgent.getToken());
                    cookie.setMaxAge(AppGlobalConstants.BLOG_USER_COOKIE_EXPIRED);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        chain.setUserId(userAgent.getId());
        chain.setId(StringUtils.getUUID32());
        chain.setCreateTime(new Date());
        chain.setModifyTime(new Date());
        chain.setAuditStatus(FriendChainAuditStatusEnum.APPLY.getValue());
        friendChainMapper.insert(chain);
        return BaseResult.<String>success().msg("提交成功！").build();
    }

    @Override
    public Page<FriendChainDto> pageChainByQuery(FriendChainQuery<FriendChain> query) {
        LambdaQueryWrapper<FriendChain> queryWrapper = buildChainQuery(query);
        friendChainMapper.selectPage(query, queryWrapper);
        return query.translateRecordsTo(FriendChainDto.class);
    }

    private BaseResult<String> checkChain(FriendChain chain) {
        if (chain == null) {
            return BaseResult.<String>error("友链信息或申请人不能为空").build();
        }
        if (StringUtils.isBlank(chain.getFriendName())) {
            return BaseResult.<String>error("请填写称呼").build();
        }
        if (StringUtils.isBlank(chain.getFriendSite())) {
            return BaseResult.<String>error("请填写网站地址").build();
        }
        return BaseResult.<String>success().build();
    }

    private LambdaQueryWrapper<FriendChain> buildChainQuery(FriendChainQuery<FriendChain> query) {
        LambdaQueryWrapper<FriendChain> queryWrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return queryWrapper;
        }
        if (!StringUtils.isBlank(query.getAuditStatus())) {
            queryWrapper.eq(FriendChain::getAuditStatus, query.getAuditStatus());
        }
        return queryWrapper;
    }
}
